{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.3895513912549688\n",
      "Model trained and predictions saved to data_with_predictions.csv\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\ProgramData\\anaconda3\\envs\\myenv2\\lib\\site-packages\\sklearn\\cluster\\_kmeans.py:1436: UserWarning: KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads. You can avoid it by setting the environment variable OMP_NUM_THREADS=7.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([1, 1, 1, ..., 0, 0, 0], dtype=int64)"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from hmmlearn import hmm\n",
    "import numpy as np\n",
    "from sklearn.metrics import confusion_matrix,accuracy_score,recall_score,f1_score,classification_report\n",
    "\n",
    "# Load the data\n",
    "data = pd.read_csv(\"D:\\Lenovo\\Desktop\\云南大学\\空间数据挖掘\\实验数据\\data9.csv\")\n",
    "\n",
    "# Extract the NDVI values and the 'Forest' states\n",
    "ndvi = data['NDVI'].values.reshape(-1, 1)\n",
    "forest = data['Forest'].values\n",
    "\n",
    "# Define and train the HMM model\n",
    "model = hmm.GaussianHMM(n_components=2, covariance_type=\"diag\", n_iter=1000)\n",
    "model.fit(ndvi)\n",
    "\n",
    "# Predict the 'Forest' states\n",
    "hidden_states = model.predict(ndvi)\n",
    "\n",
    "# Add the predictions to the DataFrame\n",
    "data['Predicted_Forest'] = hidden_states\n",
    "accurary=accuracy_score(forest,hidden_states)\n",
    "print(accurary)\n",
    "# Save the results to a new CSV file\n",
    "data.to_csv('D:\\Lenovo\\Desktop\\云南大学\\空间数据挖掘\\实验报告\\实验报告素材\\实验七\\data_with_predictions.csv', index=False)\n",
    "\n",
    "print(\"Model trained and predictions saved to data_with_predictions.csv\")\n",
    "hidden_states"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\ProgramData\\anaconda3\\envs\\myenv2\\lib\\site-packages\\sklearn\\preprocessing\\_discretization.py:239: FutureWarning: In version 1.5 onwards, subsample=200_000 will be used by default. Set subsample explicitly to silence this warning in the mean time. Set subsample=None to disable subsampling explicitly.\n",
      "  warnings.warn(\n",
      "MultinomialHMM has undergone major changes. The previous version was implementing a CategoricalHMM (a special case of MultinomialHMM). This new implementation follows the standard definition for a Multinomial distribution (e.g. as in https://en.wikipedia.org/wiki/Multinomial_distribution). See these issues for details:\n",
      "https://github.com/hmmlearn/hmmlearn/issues/335\n",
      "https://github.com/hmmlearn/hmmlearn/issues/340\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Prediction accuracy: 0.79\n",
      "Predictions saved to test_data_with_predictions.csv\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from hmmlearn import hmm\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import KBinsDiscretizer\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载数据\n",
    "data = pd.read_csv(\"D:\\Lenovo\\Desktop\\云南大学\\空间数据挖掘\\实验数据\\data9.csv\")\n",
    "\n",
    "# 提取 NDVI 值和 'Forest' 状态\n",
    "ndvi = data['NDVI'].values.reshape(-1, 1)\n",
    "forest = data['Forest'].values\n",
    "\n",
    "# 使用 KBinsDiscretizer 将 NDVI 值离散化\n",
    "discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')\n",
    "ndvi_discrete = discretizer.fit_transform(ndvi).astype(int)\n",
    "\n",
    "# 划分训练集和测试集\n",
    "ndvi_train, ndvi_test, forest_train, forest_test = train_test_split(ndvi_discrete, forest, test_size=0.3, random_state=42)\n",
    "\n",
    "# 定义和训练 HMM 模型\n",
    "model = hmm.MultinomialHMM(n_components=2, n_iter=1000, random_state=42)\n",
    "model.fit(ndvi_train)\n",
    "\n",
    "# 预测测试集的 'Forest' 状态\n",
    "forest_pred = model.predict(ndvi_test)\n",
    "\n",
    "# 评估预测准确度\n",
    "accuracy = accuracy_score(forest_test, forest_pred)\n",
    "print(f\"Prediction accuracy: {accuracy:.2f}\")\n",
    "\n",
    "# 保存结果到新的 CSV 文件\n",
    "# data_test = pd.DataFrame({'NDVI': ndvi_test.flatten(), 'Actual_Forest': forest_test, 'Predicted_Forest': forest_pred})\n",
    "# data_test.to_csv('/mnt/data/test_data_with_predictions.csv', index=False)\n",
    "\n",
    "print(\"Predictions saved to test_data_with_predictions.csv\")\n",
    "forest_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\ProgramData\\anaconda3\\envs\\myenv2\\lib\\site-packages\\sklearn\\preprocessing\\_discretization.py:239: FutureWarning: In version 1.5 onwards, subsample=200_000 will be used by default. Set subsample explicitly to silence this warning in the mean time. Set subsample=None to disable subsampling explicitly.\n",
      "  warnings.warn(\n",
      "MultinomialHMM has undergone major changes. The previous version was implementing a CategoricalHMM (a special case of MultinomialHMM). This new implementation follows the standard definition for a Multinomial distribution (e.g. as in https://en.wikipedia.org/wiki/Multinomial_distribution). See these issues for details:\n",
      "https://github.com/hmmlearn/hmmlearn/issues/335\n",
      "https://github.com/hmmlearn/hmmlearn/issues/340\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Initial state occupation distribution:\n",
      "[0.5 0.5]\n",
      "Transition matrix:\n",
      "[[0.7 0.3]\n",
      " [0.3 0.7]]\n",
      "Emission probability matrix:\n",
      "[[1.]\n",
      " [1.]]\n",
      "Prediction accuracy: 0.79\n",
      "Predictions saved to test_data_with_predictions.csv\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "       0], dtype=int64)"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from hmmlearn import hmm\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.preprocessing import KBinsDiscretizer\n",
    "from sklearn.metrics import accuracy_score\n",
    "\n",
    "# 加载数据\n",
    "data = pd.read_csv(\"D:\\Lenovo\\Desktop\\云南大学\\空间数据挖掘\\实验数据\\data9.csv\")\n",
    "\n",
    "# 提取 NDVI 值和 'Forest' 状态\n",
    "ndvi = data['NDVI'].values.reshape(-1, 1)\n",
    "forest = data['Forest'].values\n",
    "\n",
    "# 使用 KBinsDiscretizer 将 NDVI 值离散化\n",
    "discretizer = KBinsDiscretizer(n_bins=10, encode='ordinal', strategy='uniform')\n",
    "ndvi_discrete = discretizer.fit_transform(ndvi).astype(int)\n",
    "\n",
    "# 划分训练集和测试集\n",
    "ndvi_train, ndvi_test, forest_train, forest_test = train_test_split(ndvi_discrete, forest, test_size=0.3, random_state=42)\n",
    "\n",
    "# 定义和训练 HMM 模型\n",
    "model = hmm.MultinomialHMM(n_components=2, n_iter=1000, random_state=42,init_params=\"e\")\n",
    "\n",
    "# 手动初始化模型参数（可选）\n",
    "model.startprob_ = np.array([0.5, 0.5])\n",
    "model.transmat_ = np.array([[0.7, 0.3],\n",
    "                            [0.3, 0.7]])\n",
    "\n",
    "model.emissionprob_ = np.array([[0.2, 0.2, 0.2, 0.2, 0.1, 0.05, 0.05, 0, 0, 0],\n",
    "                                [0, 0, 0, 0, 0.05, 0.1, 0.15, 0.25, 0.25, 0.2]])\n",
    "\n",
    "# 训练模型\n",
    "model.fit(ndvi_train)\n",
    "\n",
    "# 查看模型参数\n",
    "print(\"Initial state occupation distribution:\")\n",
    "print(model.startprob_)\n",
    "print(\"Transition matrix:\")\n",
    "print(model.transmat_)\n",
    "print(\"Emission probability matrix:\")\n",
    "print(model.emissionprob_)\n",
    "\n",
    "# 预测测试集的 'Forest' 状态\n",
    "forest_pred = model.predict(ndvi_test)\n",
    "\n",
    "# 评估预测准确度\n",
    "accuracy = accuracy_score(forest_test, forest_pred)\n",
    "print(f\"Prediction accuracy: {accuracy:.2f}\")\n",
    "\n",
    "# 保存结果到新的 CSV 文件\n",
    "# data_test = pd.DataFrame({'NDVI': ndvi_test.flatten(), 'Actual_Forest': forest_test, 'Predicted_Forest': forest_pred})\n",
    "# data_test.to_csv('/mnt/data/test_data_with_predictions.csv', index=False)\n",
    "\n",
    "print(\"Predictions saved to test_data_with_predictions.csv\")\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "myenv2",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
